﻿using System.Xml.Serialization;
using System.Collections.Generic;
using System;

namespace Sixeyed.CacheAdapter.Configuration
{
    /// <summary>
    /// Represents a collection of <see cref="MessageCacheConfiguration"/> objects
    /// </summary>
    [XmlInclude(typeof(MessageCacheConfiguration))]
    [XmlRoot(ElementName = "messageCacheConfigurationCollection", Namespace = "http://schemas.sixeyed.com/CacheAdapter/2009")]
    public partial class MessageCacheConfigurationCollection
    {
        private MessageCacheConfiguration[] _messageCacheConfigurations;
        private Dictionary<string, MessageCacheConfiguration> _configurationDictionary = new Dictionary<string, MessageCacheConfiguration>();

        /// <summary>
        /// Gets/sets the collection of <see cref="MessageCacheConfiguration"/> objects
        /// </summary>
        [XmlArray(ElementName="messageCacheConfigurations")]
        [XmlArrayItem(ElementName = "messageCacheConfiguration")]
        public MessageCacheConfiguration[] MessageCacheConfigurations
        {
            get { return this._messageCacheConfigurations; }
            set 
            { 
                this._messageCacheConfigurations = value;
                this.LoadDictionary();
            }
        }

        /// <summary>
        /// Returns whether the given message type is configured for caching
        /// </summary>
        /// <param name="messageType">BizTalk message type</param>
        /// <returns>Whether caching is enabled</returns>
        public bool IsMessageCacheEnabled(string messageType)
        {
            return this._configurationDictionary.ContainsKey(messageType);
        }

        /// <summary>
        /// Returns the configured cache lifepan for the given message type 
        /// </summary>
        /// <param name="messageType">BizTalk message type</param>
        /// <returns>Configured lifespan, or TimeSpan.Zero if none configured</returns>
        public TimeSpan GetMessageCacheLifespan(string messageType)
        {
            TimeSpan cacheLifespan = TimeSpan.Zero;
            if (IsMessageCacheEnabled(messageType))
            {
                cacheLifespan = _configurationDictionary[messageType].CacheLifespan;
            }
            return cacheLifespan;
        }

        private void LoadDictionary()
        {
            //add the config items to a dictionary for ease of lookup:
            _configurationDictionary = new Dictionary<string, MessageCacheConfiguration>(this._messageCacheConfigurations.Length);
            foreach (MessageCacheConfiguration configuration in this._messageCacheConfigurations)
            {
                _configurationDictionary.Add(configuration.MessageType, configuration);
            }
        }
    }
}
